<template>
  <div>
    <el-card class="box-card" style="margin:20px">
      <div slot="header" class="clearfix">
        <el-form :inline="true">
          <el-form-item label="名称" style="margin-bottom:0px;">
            <el-input v-model="searchName" placeholder="输入名称" />
          </el-form-item>
          <el-form-item label="编码" style="margin-bottom:0px;">
            <el-input v-model="searchForm.code" placeholder="输入编码" />
          </el-form-item>
          <el-form-item label="所属系统" style="margin-bottom:0px;">
            <el-select
              v-model="searchForm.systemId"
              placeholder="请选择"
              style="width: 100%"
            >
              <el-option
                v-for="item in systemOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>

          </el-form-item>
          <el-form-item label="模板" style="margin-bottom:0px;">
            <el-input v-model="searchForm.templateName" placeholder="输入模板名称" />
          </el-form-item>
          <el-form-item label="流程" style="margin-bottom:0px;">
            <el-input v-model="searchForm.flowName" placeholder="输入流程名称" />
          </el-form-item>
          <el-form-item style="margin-bottom:0px;">
            <el-button type="primary" icon="el-icon-search" @click="getItemList">查询</el-button>
            <el-button type="primary" icon="el-icon-edit" @click="add">新增</el-button>
          </el-form-item>
        </el-form>
      </div>
      <el-table v-loading="loading" :data="tableData" style="width: 100%">
        <el-table-column
          prop="name"
          label="名称"
          min-width="30%"
        />
        <el-table-column
          prop="code"
          label="编码"
          min-width="30%"
        />
        <el-table-column
          prop="systemName"
          label="所属系统"
          min-width="30%"
        />
        <el-table-column
          prop="templateName"
          label="模板"
          min-width="30%"
        />
        <el-table-column
          prop="flowName"
          label="流程"
          min-width="30%"
        />
        <el-table-column
          prop="updateTime"
          label="更新时间"
          min-width="24%"
        />
        <el-table-column
          align="center"
          label="操作"
        >
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="warning"
              icon="el-icon-edit"
              @click="update(scope.$index, scope.row)"
            >
              编辑
            </el-button>
            <el-button
              size="mini"
              type="danger"
              icon="el-icon-edit-delete"
              @click="remove(scope.$index, scope.row)"
            >
              删除
            </el-button>
            <el-button
              size="mini"
              type="primary"
              icon="el-icon-document"
              @click="editForm(scope.$index, scope.row)"
            >
              模板
            </el-button>
            <el-button
              size="mini"
              type="success"
              icon="el-icon-edit-outline"
              @click="editFlow(scope.$index, scope.row)"
            >
              流程
            </el-button>
            <el-button
              size="mini"
              type="success"
              icon="el-icon-edit-outline"
              @click="startApply(scope.$index, scope.row)"
            >
              发起申请
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="block" style="float:right;margin:20px">
        <el-pagination
          :current-page="currentPage"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
      <div>
        <!-- 新增事项 -->
        <el-dialog title="事项信息" :visible.sync="dialogItemVisible">
          <el-form ref="itemForm" label-width="100px" size="mini" :model="itemForm" :rules="rules">
            <el-form-item label="事项名称" prop="itemName">
              <el-input
                v-model="itemForm.itemName"
              />
            </el-form-item>
            <!-- <el-form-item label="事项编码" prop="itemCode">
              <el-input
                v-model="itemForm.itemCode"
              />
            </el-form-item> -->
            <el-form-item label="所属系统" prop="systemId">
              <el-select
                v-model="itemForm.systemId"
                :disabled="updateItemId != 0"
                placeholder="请选择"
                style="width: 100%"
              >
                <el-option
                  v-for="item in systemOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogItemVisible = false">取 消</el-button>
            <el-button type="primary" @click="addOrUpdate">确 定</el-button>
          </div>
        </el-dialog>
        <!-- 表单模板列表 -->
        <el-dialog title="模板" :visible.sync="dialogFormVisible">
          <div>
            <el-table height="350" :data="formData" style="width: 100%">
              <el-table-column
                prop="name"
                label="名称"
                min-width="60%"
              />
              <el-table-column
                prop="code"
                label="编码"
                min-width="60%"
              />
              <el-table-column
                prop="version"
                label="版本"
                min-width="20%"
              />
              <el-table-column
                align="center"
                label="操作"
              >
                <template slot-scope="scope">
                  <el-button
                    v-if="scope.row.id != bindFormId"
                    size="mini"
                    type="success"
                    @click="bindForm(scope.$index, scope.row)"
                  >
                    绑定
                  </el-button>
                  <el-button
                    v-if="scope.row.id == bindFormId"
                    size="mini"
                    type="danger"
                  >
                    已绑定
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div slot="footer" class="dialog-footer">
            <el-pagination
              :current-page="formCurrentPage"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="formPageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="formTotal"
              @size-change="formHandleSizeChange"
              @current-change="formHandleCurrentChange"
            />
          </div>
        </el-dialog>
        <!-- 流程列表 -->
        <el-dialog title="流程" :visible.sync="dialogFlowVisible">
          <div>
            <el-table height="350" :data="flowData" style="width: 100%">
              <el-table-column
                prop="name"
                label="名称"
                min-width="60%"
              />
              <el-table-column
                prop="flowKey"
                label="流程KEY"
                min-width="60%"
              />
              <el-table-column
                align="center"
                label="操作"
              >
                <template slot-scope="scope">
                  <el-button
                    v-if="scope.row.id != bindFlowId"
                    size="mini"
                    type="success"
                    @click="bindFlow(scope.$index, scope.row)"
                  >
                    绑定
                  </el-button>
                  <el-button
                    v-if="scope.row.id == bindFlowId"
                    size="mini"
                    type="danger"
                  >
                    已绑定
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
          <div slot="footer" class="dialog-footer">
            <el-pagination
              :current-page="flowCurrentPage"
              :page-sizes="[10, 20, 50, 100]"
              :page-size="flowPageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="flowTotal"
              @size-change="flowHandleSizeChange"
              @current-change="flowHandleCurrentChange"
            />
          </div>
        </el-dialog>
      </div>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    var validateItemCode = (rule, value, callback) => {
      if (value === '') {
        callback(new Error('请输入事项编码'))
      } else {
        if (this.itemForm.itemCode !== '') {
          const params = new FormData()
          params.append('itemCode', this.itemForm.itemCode)
          params.append('updateItemId', this.updateItemId)
          this.$axios.post(this.baseItemUrl + '/item/validateItemCode',
            params
          ).then(res => {
            if (res.data.data) {
              callback()
            } else {
              callback(new Error('事项编码已存在，请重新输入'))
            }
          }).catch(() => {
            callback(new Error('请重新输入事项编码'))
            this.$message.error('事项编码校验失败')
          })
        }
      }
    }
    return {
      fullscreen: true,
      routeData: this.$route.params,
      tableData: [],
      currentPage: 1,
      pageSize: 10,
      total: 0,
      dialogItemVisible: false,
      itemForm: {
        itemName: '',
        itemCode: '',
        systemId: ''
      },
      rules: {
        itemName: [
          { required: true, message: '请输入事项名称', trigger: 'blur' }
        ],
        itemCode: [
          { validator: validateItemCode, trigger: 'blur' }
        ],
        systemId: [
          { required: true, message: '请选择业务系统', trigger: 'change' }
        ]
      },
      updateItemId: 0,
      systemOptions: [],
      dialogFormVisible: false,
      formData: [],
      formCurrentPage: 1,
      formPageSize: 10,
      formTotal: 0,
      searchName: '',
      bindFormId: 0,
      dialogFlowVisible: false,
      flowData: [],
      bindFlowId: 0,
      flowCurrentPage: 1,
      flowPageSize: 10,
      flowTotal: 0,
      loading: false,
      systemId: '',
      searchForm: {
        code: '',
        systemName: '',
        templateName: '',
        flowName: ''
      }
    }
  },
  created() {
    if (this.routeData.itemCurrentPage != null && this.routeData.itemPageSize != null) {
      this.currentPage = this.routeData.itemCurrentPage
      this.pageSize = this.routeData.itemPageSize
    }
  },
  mounted() {
    this.getItemList()
    this.getSystemOptions()
  },
  methods: {
    getItemList: function() {
      this.loading = true
      var params = {
        'pageSize': this.pageSize,
        'pageNum': this.currentPage,
        'name': this.searchName,
        'code': this.searchForm.code,
        'systemId': this.searchForm.systemId,
        'templateName': this.searchForm.templateName,
        'flowName': this.searchForm.flowName
      }
      this.$axios.get(this.baseItemUrl + '/item/page', {
        params
      }).then(res => {
        this.tableData = res.data.data.records
        this.total = parseInt(res.data.data.total)
        this.loading = false
      }).catch(() => {
        this.loading = false
        this.$message.error('获取模板列表失败')
      })
    },
    show: function(index, row) {
      this.$router.push({ name: 'view', params: row })
    },
    edit: function(index, row) {
      this.$router.push({ name: 'template', params: row })
    },
    addOrUpdate() {
      this.$refs['itemForm'].validate((valid) => {
        if (valid) {
          var params = {
            'name': this.itemForm.itemName,
            // 'code': this.itemForm.itemCode,
            'systemId': this.itemForm.systemId
          }
          var url = this.baseItemUrl + '/item/saveItem'
          if (this.updateItemId != 0) {//eslint-disable-line
            url = this.baseItemUrl + '/item/update'
            this.$set(params, 'id', this.updateItemId)
          }
          this.$axios.post(url,
            params
          ).then(res => {
            this.$message.success('操作成功~')
            this.dialogItemVisible = false
            this.getItemList()
          }).catch(() => {
            this.$message.error('操作失败！')
          })
        } else {
          this.$message.error('请正确输入')
          return false
        }
      })
    },
    remove: function(index, row) {
      this.$confirm('此操作将永久删除该模板, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
        center: true
      }).then(() => {
        this.$axios.delete(this.baseItemUrl + '/item', {
          params: {
            itemId: row.id
          }
        }).then(res => {
          if (res.data.code === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            })
            this.getItemList()
          } else {
            this.$message({
              type: 'error',
              message: res.data.msg
            })
          }
        }).catch(() => {
          this.$message({
            type: 'error',
            message: '删除失败'
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.getItemList()
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getItemList()
    },
    add() {
      if (this.$refs['itemForm'] !== undefined) {
        this.$refs['itemForm'].resetFields()
      }
      // this.$set(this.itemForm, 'itemCode', '')
      this.$set(this.itemForm, 'itemName', '')
      this.$set(this.itemForm, 'systemId', '')
      this.updateItemId = 0
      this.dialogItemVisible = true
    },
    update(index, row) {
      if (this.$refs['itemForm'] !== undefined) {
        this.$refs['itemForm'].resetFields()
      }
      // this.$set(this.itemForm, 'itemCode', row.code)
      this.$set(this.itemForm, 'itemName', row.name)
      this.$set(this.itemForm, 'systemId', row.systemId)
      this.updateItemId = row.id
      this.dialogItemVisible = true
    },
    getSystemOptions() {
      this.$axios.get(this.basePortalUrl + '/system/findAll'
      ).then(res => {
        this.systemOptions = res.data.data
      }).catch(() => {
        this.$message.error('获取业务系统失败')
      })
    },
    getFormList() {
      var params = {
        'pageSize': this.formPageSize,
        'pageNum': this.formCurrentPage,
        'systemId': this.systemId
      }
      if (this.bindFormId) {
        params['templateId'] = this.bindFormId
      }
      this.$axios.get(this.baseFormUrl + '/template/item/page',
        { params }).then(res => {
        this.formData = res.data.data.records
        this.formTotal = parseInt(res.data.data.total)
      }).catch(() => {
        this.$message.error('获取模板列表失败')
      })
    },
    editForm(index, row) {
      this.systemId = row.systemId
      this.formData = []
      this.formTotal = 0
      this.formCurrentPage = 1
      this.formPageSize = 10
      this.updateItemId = row.id
      this.bindFormId = row.templateId
      this.getFormList()
      this.dialogFormVisible = true
      // this.$router.push({ name: 'templateList',
      //   params: {
      //     'itemId': row.id,
      //     'itemName': row.name,
      //     'templateId': row.templateId,
      //     'itemCurrentPage': this.currentPage,
      //     'itemPageSize': this.pageSize
      //   }
      // })
    },
    formHandleSizeChange(val) {
      this.formPageSize = val
      this.formCurrentPage = 1
      this.getFormList()
    },
    formHandleCurrentChange(val) {
      this.formCurrentPage = val
      this.getFormList()
    },
    bindForm(index, row) {
      var params = {
        'id': this.updateItemId,
        'templateId': row.id
      }
      this.$axios.post(this.baseItemUrl + '/item/update',
        params
      ).then(res => {
        this.$message.success('绑定成功~')
        this.updateItemId = 0
        this.bindFormId = 0
        this.getItemList()
        this.dialogFormVisible = false
      }).catch(() => {
        this.$message.error('绑定失败！')
      })
    },
    flowHandleSizeChange(val) {
      this.flowPageSize = val
      this.flowCurrentPage = 1
      this.getFlowList()
    },
    flowHandleCurrentChange(val) {
      this.flowCurrentPage = val
      this.getFlowList()
    },
    editFlow(index, row) {
      this.systemId = row.systemId
      this.getFlowList()
      this.flowCurrentPage = 1
      this.flowPageSize = 10
      this.updateItemId = row.id
      this.bindFlowId = row.flowId
      this.dialogFlowVisible = true
      // this.$router.push({ name: 'designList',
      //   params: {
      //     'itemId': row.id,
      //     'itemName': row.name,
      //     'flowId': row.flowId,
      //     'itemCurrentPage': this.currentPage,
      //     'itemPageSize': this.pageSize
      //   }
      // })
    },
    getFlowList() {
      var params = {
        'pageSize': this.flowPageSize,
        'pageNum': this.flowCurrentPage,
        'name': '',
        'systemId': this.systemId
      }
      this.$axios.get(this.baseFlowUrl + '/flow/systemId/page', {
        params
      }).then(res => {
        this.flowData = res.data.data.records
        this.flowTotal = parseInt(res.data.data.total)
      }).catch(() => {
        this.$message.error('获取流程列表失败')
      })
    },
    bindFlow(index, row) {
      var params = {
        'id': this.updateItemId,
        'flowId': row.id
      }
      this.$axios.post(this.baseItemUrl + '/item/update',
        params
      ).then(res => {
        this.$message.success('绑定成功~')
        this.updateItemId = 0
        this.bindFlowId = 0
        this.getItemList()
        this.dialogFlowVisible = false
      }).catch(() => {
        this.$message.error('绑定失败！')
      })
    },
    startApply(index, row) {
      this.applyTitle = row.name
      // 根据系统不同，获取不同url
      this.$axios.get(this.basePortalUrl + '/system/getById/' + row.systemId)
        .then(res => {
          const src = res.data.data.applyUrl + '?businessCode=' + this.uuid() + '&itemCode=' + row.code + '&action=create'
          window.open(src, '_black')
        }).catch(() => {
          this.loading = false
          this.$message.error('获取模板列表失败')
        })
    },
    uuid() {
      var temp_url = URL.createObjectURL(new Blob())
      var uuid = temp_url.toString() // blob:https://xxx.com/b250d159-e1b6-4a87-9002-885d90033be3
      URL.revokeObjectURL(temp_url)
      return uuid.substr(uuid.lastIndexOf('/') + 1)
    }
  }
}
</script>
<style lang="scss" scoped>

</style>
